from paddleocr import PaddleOCR
import asyncio
import aiohttp
import os
import tempfile


async def ocr_recognize_picture_by_url(url):
    """从URL下载图片，OCR识别，然后删除临时文件"""
    temp_file = None
    try:
        # 下载图片并判断格式
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as response:
                content = await response.read()
                
                # 根据文件头判断图片格式
                if content.startswith(b'\xff\xd8\xff'):
                    suffix = '.jpg'
                elif content.startswith(b'\x89PNG'):
                    suffix = '.png'
                elif content.startswith(b'GIF8'):
                    suffix = '.gif'
                elif content.startswith(b'BM'):
                    suffix = '.bmp'
                elif content.startswith(b'RIFF') and b'WEBP' in content[:12]:
                    suffix = '.webp'
                else:
                    suffix = '.jpg'  # 默认格式
                
                # 创建temp目录并保存文件
                temp_dir = os.getcwd()
                os.makedirs(temp_dir, exist_ok=True)
                temp_file = os.path.join(temp_dir, f"temp_image{suffix}")
                print(f"保存图片到: {temp_file}")
                with open(temp_file, 'wb') as f:
                    f.write(content)
                print(f"图片保存成功，文件大小: {len(content)} bytes")
        
        # OCR识别
        ocr = PaddleOCR(use_doc_orientation_classify=False, use_doc_unwarping=False, 
                       use_textline_orientation=False, ocr_version="PP-OCRv5")
        result = ocr.predict(temp_file)
        
        # 提取所有识别的文字
        texts = []
        for res in result:
            texts.extend(res["rec_texts"])
        
        # 用换行符连接所有文字
        text_result = '\n'.join(texts)
        
        # 输出结果
        print(text_result)
        
        return text_result
        
    except Exception as e:
        print(f"处理出错: {e}")
        return ""
    finally:
        # 删除临时文件
        if temp_file and os.path.exists(temp_file):
            os.remove(temp_file)


if __name__ == '__main__':
    url = "http://localhost/files/d3519d77-faa1-41ca-8036-0d6a0a751dfe/file-preview?timestamp=1761016564&nonce=7c380f1c4b1ee54cbb2f03a163a586dc&sign=UYqBbr0NEie9lMFEb5G-RWn2gfFP8_r8fSPVAPA5ZE8="
    result = asyncio.run(ocr_recognize_picture_by_url(url))
    print("最终结果:", result)